#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;

    string replaceSpaces(string S, int length) {
        int count = 0;
        for (const auto& e : S)
        {
            if (e == ' ')
            {
                count++;
            }
        }
        S[count * 2 + length] = '\0';
        int stp1 = count * 2 + length - 1;
        int stp2 = length - 1;
        while (stp2 >= 0)
        {
            if (S[stp2--] == ' ')
            {
                S[stp1--] = '0';
                S[stp1--] = '2';
                S[stp1--] = '%';
                continue;
            }
            S[stp1--] = S[stp2--];
        }
        return S;
    }

    int main()
    {
        replaceSpaces("abcd ", 5);
        return 0;
    }

    class Solution {
    public:
        string replaceSpaces(string S, int length) {
            int count = 0;
            for (int i = 0; i < length; i++)
            {
                if (S[i] == ' ')
                {
                    count++;
                }
            }
            S[count * 2 + length] = '\0';
            int stp1 = count * 2 + length - 1;
            int stp2 = length - 1;
            while (stp2 >= 0)
            {
                if (S[stp2] == ' ')
                {
                    S[stp1--] = '0';
                    S[stp1--] = '2';
                    S[stp1--] = '%';
                    stp2--;
                    continue;
                }
                S[stp1--] = S[stp2--];
            }
            return S;
        }
    };